import axios, {AxiosError, AxiosInstance} from "axios";
import {IResponseData, ZJRequestConfig} from "@/services/types";
import {message} from "ant-design-vue";
import useGlobalStore from "@/store/globalModule";
import router from "@/router";
import {localCache} from "@/utils";
import useAccountStore from "@/store/accountModule";

class ZJRequest {
    request: AxiosInstance
    count: number
    globalStore: any
    accountStore: any

    constructor(config?: ZJRequestConfig) {
        this.request = axios.create(config)
        this.count = 0
        this.globalStore = null
        this.accountStore = null
        // 添加请求拦截器
        this.request.interceptors.request.use(config => {
            this.count += 1
            this.globalStore = useGlobalStore()
            this.accountStore = useAccountStore()
            this.globalStore.setIsShowAction(true)
            return config;
        }, (error) => {
            this.globalStore.setIsShowAction(false)
            return Promise.resolve(error);
        });

        // 添加响应拦截器
        this.request.interceptors.response.use((response) => {
            // 控制加载圈圈
            this.count -= 1
            if (this.count === 0) {
                this.globalStore.isShow = false
            }
            const data: IResponseData = response.data
            if (data.code !== 0) {
                let errorMsg = "操作失败：" + response.data.msg
                if (data.code === -2) { // 未登录
                    errorMsg = "暂未登录"
                    this.accountStore.resetAccountAction()
                }
                message.error(errorMsg)
            }
            return data;
        }, (error: AxiosError) => {
            this.globalStore.setIsShowAction(false)
            this.count -= 1
            const err: IResponseData = {
                code: -1,
                msg: error.message,
                data: error
            }
            message.error("请求失败" + error.message)
            return Promise.resolve(err);
        });
    }

    get(config: ZJRequestConfig) {
        const {url = "", ...realConfig} = config
        return this.request.get<any, IResponseData>(url, realConfig)
    }

    post(config: ZJRequestConfig) {
        const {url = "", data = {}, ...realConfig} = config
        return this.request.post<any, IResponseData>(url, data, realConfig)
    }
}

export default ZJRequest
